package com.ruoyi.project.erp.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.erp.dto.AddProjectBySalesDTO;
import com.ruoyi.project.erp.dto.CreateProjectDto;
import com.ruoyi.project.erp.dto.ProjectDto;
import com.ruoyi.project.erp.dto.ProjectQuery;
import com.ruoyi.project.erp.vo.ProjectInfoVo;
import com.ruoyi.project.erp.vo.ProjectVo;
import com.ruoyi.project.system.domain.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.erp.domain.Project;
import com.ruoyi.project.erp.service.IProjectService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 项目Controller
 *
 * @author ruoyi
 * @date 2025-06-17
 */
@RestController
@RequestMapping("/erp/project")
public class ProjectController extends BaseController {
    @Autowired
    private IProjectService projectService;

    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('erp:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectQuery query) {
        startPage();
        List<ProjectVo> list = projectService.selectList(query);
        return getDataTable(list);
    }



    @GetMapping("/projectList")
    public AjaxResult projectList() {
        List<Project> list = projectService.selectAllProject();
        return AjaxResult.success(list);
    }
    /**
     * 查询项目列表
     */
    @PreAuthorize("@ss.hasPermi('erp:project:list')")
    @GetMapping("/currentProjects")
    public TableDataInfo currentProjects(ProjectDto dto) {
        startPage();
        List<ProjectVo> list = projectService.currentProjects(dto);
        return getDataTable(list);
    }

    /**
     * 查询项目详情
     */
    @GetMapping("/queryProjectInfo")
    public AjaxResult queryProjectInfo(@RequestParam("project") String projectId) {
        ProjectInfoVo vo = projectService.queryProjectInfo(projectId);
        return success(vo);
    }

    /**
     * 导出项目列表
     */
    @PreAuthorize("@ss.hasPermi('erp:project:export')")
    @Log(title = "项目", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Project project) {
        List<Project> list = projectService.selectProjectList(project);
        ExcelUtil<Project> util = new ExcelUtil<Project>(Project.class);
        util.exportExcel(response, list, "项目数据");
    }

    /**
     * 获取项目详细信息
     */
//    @PreAuthorize("@ss.hasPermi('erp:project:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult getInfo(@PathVariable("id") Long id) {
//        return success(projectService.selectProjectById(id));
//    }
    /**
     * 【新增接口】获取用于前端回显的项目详细视图信息
     * @param id 项目主键ID
     * @return AjaxResult 包含 ProjectVo 对象
     */
    @PreAuthorize("@ss.hasPermi('erp:project:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getProjectVoInfo(@PathVariable("id") Long id)
    {
        // 从安全上下文中获取当前登录用户的ID
        Long userId = SecurityUtils.getUserId();
        // 调用我们新增的service方法
        ProjectVo projectVo = projectService.selectProjectVoById(id, userId);
        return success(projectVo);
    }
    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('erp:project:add')")
    @Log(title = "项目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Project project) {
        return toAjax(projectService.insertProject(project));
    }


    /**
     * 新增项目
     */
    @PreAuthorize("@ss.hasPermi('erp:project:add')")
    @Log(title = "创建项目", businessType = BusinessType.INSERT)
    @PostMapping("/createProject")
    public AjaxResult createProject(@RequestBody CreateProjectDto dto) {
        return toAjax(projectService.createProject(dto));
    }

    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('erp:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PostMapping("/editProject")
    public AjaxResult editProject(@RequestBody CreateProjectDto dto) {
        return toAjax(projectService.editProject(dto));
    }


    /**
     * 修改项目
     */
    @PreAuthorize("@ss.hasPermi('erp:project:edit')")
    @Log(title = "项目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Project project) {
        return toAjax(projectService.updateProject(project));
    }

    /**
     * 删除项目
     */
    @PreAuthorize("@ss.hasPermi('erp:project:remove')")
    @Log(title = "项目", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(projectService.deleteProjectByIds(ids));
    }



    /**
     * 通过Excel文件导入项目数据
     * @param file 用户上传的Excel文件
     * @param updateSupport 如果项目编号已存在，是否覆盖更新
     * @return 操作结果
     */
    @Log(title = "项目管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        // 1. 文件非空校验
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("导入数据失败，请选择要上传的Excel文件！");
        }

        try {
            // 2. 【推荐】获取当前操作人的【登录用户名】，它在系统中是唯一的
            String operName = SecurityUtils.getUsername();

            // 3. 【推荐】向Service层传递文件的输入流（InputStream），而不是整个MultipartFile对象
            String message = projectService.importProject(file.getInputStream(), updateSupport, operName);

            return AjaxResult.success(message);
        } catch (Exception e) {
            // 4. 统一处理异常，返回给前端
            // 如果Service层抛出了ServiceException或其他异常，在这里捕获并返回错误信息
            return AjaxResult.error(e.getMessage());
        }
    }



    @PostMapping("/addProjectBySales")
    public AjaxResult  addProjectBySales(@RequestBody AddProjectBySalesDTO addProjectBySalesDTO){
        projectService.addProjectBySales(addProjectBySalesDTO);
        return AjaxResult.success();
    }
}
